function getLocalStorage(key) {
	if (!localStorage) {
		return null;
	}
	return localStorage.getItem(key);
}

function  setLocalStorage(key, value) {
	if (!localStorage) {
		return;
	}
	return localStorage.setItem(key, value);
}


function geoLocation(opt) {
	var option = {
		after: opt.after ? opt.after : function(){},
		before: opt.before ? opt.before : function(){},
		error: opt.error ? opt.error : function(){},
		isRefresh: opt.isRefresh,
		isWatch: opt.isWatch
	};
	var KEY = "geoPosition";
	var watchId = -1;
	var position = getLocalStorage(KEY);
	
	if (!option.isRefresh && position) {
		
		var latLng = position.split(",");
		option.after(latLng[0], latLng[1]);
		
		if (option.isWatch) {
			getLocation_();
		} else {
			// 仅为了刷新位置缓存
			option.after = function(){};
			option.before = function(){};
			option.error = function(){};
			getLocation_();
		}
		
	} else {
		getLocation_();
	}
	
	function getLocation_() {
		if (navigator.geolocation) {
			var geoOptions = {
				//enableHighAccuracy: true,
				//timeout: 20000
			};
			option.before();
			if (option.isWatch) {
				watchId = navigator.geolocation.watchCurrentPosition(showPosition_, showError_, geoOptions);
			} else {
				navigator.geolocation.getCurrentPosition(showPosition_, showError_, geoOptions);
			}
			
	    } else {
	    	option.error("当前浏览器不支持位置信息");
	    }
	}
	
	
	function showPosition_(position) {
		
		var lat=position.coords.latitude;
		var lng=position.coords.longitude;
		
		setLocalStorage(KEY, lat + "," + lng);
		
		option.after(lat, lng);
		
	}
	
	function showError_(error) {
		
		navigator.geolocation.clearWatch(watchId);
		
		switch(error.code) {
		case error.PERMISSION_DENIED:
			option.error("位置信息未启用");
		  break;
		case error.POSITION_UNAVAILABLE:
			option.error("位置信息不可用");
		  break;
		case error.TIMEOUT:
			option.error("位置信息获取超时");
		  break;
		case error.UNKNOWN_ERROR:
			option.error("位置信息错误");
		  break;
		}
	}
};

/**
 * 两经纬度距离(单位:米)
 * @param latA
 * @param lngA
 * @param latB
 * @param lngB
 * @returns {Number}
 */
function getDistance(latA, lngA, latB, lngB) {
	var EARTH_RADIUS = 6378137.0;
	var radLat1 = (latA * Math.PI / 180.0);
	var radLat2 = (latB * Math.PI / 180.0);
	var a = radLat1 - radLat2;
	var b = (lngA - lngB) * Math.PI / 180.0;
	var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
			+ Math.cos(radLat1) * Math.cos(radLat2)
			* Math.pow(Math.sin(b / 2), 2)));
	s = s * EARTH_RADIUS;
	s = Math.round(s * 10000) / 10000;
	return s;
}

//日期类扩展
Date.prototype.format = function(fmt) { //author: meizz   
  var o = {   
    "M+" : this.getMonth()+1,                 //月份   
    "d+" : this.getDate(),                    //日   
    "h+" : this.getHours(),                   //小时   
    "m+" : this.getMinutes(),                 //分   
    "s+" : this.getSeconds(),                 //秒   
    "q+" : Math.floor((this.getMonth()+3)/3), //季度   
    "S"  : this.getMilliseconds()             //毫秒   
  };   
  if(/(y+)/.test(fmt)) {
  	fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));  
  }  
     
  for(var k in o) {
    if(new RegExp("("+ k +")").test(fmt))   {
  		fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));   
    }
  }
  return fmt;   
};

$("link[rel='dns-prefetch']").each(function() {
	eval("g_" + $(this).attr("id") + "='" + $(this).attr("href") + "';");
});

$("<iframe>").hide().attr("src", g_resDomain + "/page/html/manifest.html").appendTo("body");

var mxz =  {};
(function($) {
	mxz.pluginLoader = new (function() {
		var plugins_ = {
				msgbox: {
					isLoaded: false,
					js:[
					    "/common/js/msgbox/jquery.msgbox.min.js",
					    "/common/js/msgbox/jquery.msgbox.i18n.js"
					   ],
					css:[
					     "/common/js/msgbox/themes/metro/css/jquery.msgbox.css"
					    ]
				},
				datepicker: {
					isLoaded: false,
					js:["/common/js/datepicker/WdatePicker.js"],
					css:["/common/js/datepicker/skin/WdatePicker.css"]
				},
				pagectrl: {
					isLoaded: false,
					js:["/common/js/pagectrl.js"],
					css:[]
				},
				fun: {
					isLoaded: false,
					js:["/common/js/fun.js"],
					css:[]
				},
				category: {
					isLoaded: false,
					js:["/scripts/category.js"],
					css:[]
				},
				validator: {
					isLoaded: false,
					js:[
					    "/scripts/validator-0.7.3/jquery.validator.js",
					    "/scripts/validator-0.7.3/local/zh_CN.js"
					   ],
					css:["/scripts/validator-0.7.3/jquery.validator.css"]
				}
		};
		var load_ = function(name, callback) {
			var plugin = plugins_[name];
			if (!plugin) {
				console?console.log("找不到插件:" + name):void(0);
				return;
			}
			if (plugin.isLoaded) {
				callback?callback():void(0);
				return;
			}
			
			var len = plugin.css.length;
			for (var i = 0; i< len; i++) {
				var cssPath = plugin.css[i];
				if (cssPath.indexOf("/") == 0) {
					cssPath = g_resDomain + cssPath;
				}
				$("head").append('<link href="' + cssPath + '" rel="stylesheet" type="text/css" />');
			}
			
			loadJs(plugin.js,0);
			
			function loadJs(jsPaths,i) {
				var jsPath = jsPaths[i];
				if(!jsPath)return;
				
				if (jsPath.indexOf("/") == 0) {
					jsPath = g_resDomain + jsPath;
				}
				$.getScript(jsPath, function() {
					if (i + 1 == jsPaths.length) {
						plugins_[name].isLoaded = true;
						plugin.callback?plugin.callback():void(0);
						callback?callback():void(0);
					} else {
						loadJs(jsPaths,i + 1);
					}
				});
			}
		};
		var loads_ = function (names, callback) {
			var isLoadedAll = true;
			for (var i = 0; i< names.length; i++) {
				if (!plugins_[names[i]].isLoaded) {
					load_(names[i]);
					isLoadedAll = false;
				}
			}
			if (callback) {
				if (isLoadedAll) {
					callback();
				} else {
					setTimeout(function() {
						loads_(names, callback);
					}, 100);
				}
			}
			
		};
		
		var pluginLoader_ = {
			load: load_,
			loads: loads_
		};
		return pluginLoader_;
	})();
	
	
})(jQuery);

var Login = (function() {
	var loadLoginfo_ = function(callback) {
		if (!sessionStorage.loginfo) {
			$.post(g_domain + "/member/loginfo/json", function(data) {
				var obj;
				try {
					obj = $.parseJSON(data);
					if (obj.result) {
						sessionStorage.loginfo = data;
					}
				} catch (e) {}
				
				if (obj && callback) callback(obj.result);
				
			}, 'text');
		} else {
			var obj;
			try {
				obj = $.parseJSON(sessionStorage.loginfo);
			} catch (e) {}
			
			if (obj && callback) callback(obj.result);
		}
	} 
	var loginDialog_ = function(callback) {
		$("head").append('<link id="loginCss_1" href="' + g_resDomain + '/css/login.css" rel="stylesheet"/>');
   		
		var $defBody = $("#defBody"),$loginBody = $("#loginBody");
		if ($defBody.length > 0) {
			$defBody.hide();
			$loginBody.show();
			return;
		} else {
			$defBody = $('<div id="defBody"><div>').append($("body").children()).appendTo("body");
			$loginBody = $('<div id="loginBody"><div>').appendTo("body");
		}
		
		$loginBody.load(g_resDomain + "/page/html/login.html", function() {
			$defBody.hide();
	   		$("#exitLoginDialog").click(function () {
	   			$("[id^='loginCss_']").remove();
	   			$defBody.show();
	   			$loginBody.hide();
	   		});
	   		$("#registerNew").click(function () {
	   			location.href = g_domain + "/member/register";
	   		});
	   		$("#forgetPwd").click(function () {
	   			location.href = g_domain + "/member/forgetPwd";
	   		});
	   		var $form = $("#loginForm");
			mxz.pluginLoader.load("validator",init);
			function init() {
				$form.validator({
					fields: {
						name: "账户名:required",
						password: "密码:required"
					},
					valid: function(form){
						showMsg("正在登录...", "load");
						var me = this;
						me.holdSubmit();
						$.post(g_domain + "/member/loginDo/json",$(form).serialize(), function(data){
								if (data.status != 0) {
									me.holdSubmit(false);
									showMsg(data.message, "error");
									return;
								} 
								showMsg("登录成功...", "pass");
								$("[id^='loginCss_']").remove();
								$defBody.show();
					   			$loginBody.hide();
								callback? callback():void(0);
						});
					}
				});
			}
	   	});
	}
	var checkLogin_ = function(callback) {
		loadLoginfo_(function(loginfo) {
			if (!loginfo) {
		    	loginDialog_(callback);
		    } else {
		    	callback? callback():void(0);
		    }
		});
	}
	
	return {
		getLoginfo: loadLoginfo_,
		checkLogin: checkLogin_,
		login: loginDialog_
	}

})();

$(document).ajaxComplete(function(event,request, settings){
	if (request.status == 200 && request.responseText == "-1") {
		Login.login();
		return false;
	}
});

// 访问日志
(function() {
	$.post(g_behaviorDomain + "/accessLog/json", {url: location.href});
})();

// 图片懒加载
$(function() {
	var isDoing = false;
	$(document).on('showimg', function() {
		if (isDoing) {
			return;
		}
		setTimeout(function() {
			isDoing = true;
			var wHeight = $(window).height();
			var wScrollTop = $(window).scrollTop();
			$("img[data][dtype!='tmp']").each(function() {
				var $this = $(this);
				var elHeight = $this.height();
				var elTop = $this.offset().top;
				if ((wScrollTop >= elTop && wScrollTop < (elTop + elHeight)) || (wScrollTop < elTop && (wScrollTop + wHeight) >= elTop) ) {
					var src = $this.attr("data");
					if (src.indexOf("http") != 0) {
						src = g_attaDomain + src;
					}
					$this.attr("src", src);
					$this.removeAttr("data");
				}
			});
			isDoing = false;
		}); 
	});
	$(window).scroll(function() {
		$(document).trigger('showimg');
	});
	$(document).trigger('showimg');
});

/**
 *	刷新购物车物品数量
 */
 function shoppingCount(bool) {
	var $count_ =  $("#shoppingCount");
	if (!bool && $count_.length == 0) {
		return;
	}
	var getCountPath_ = g_userDomain + "/shopping/amount/json";
	
	if (bool || !sessionStorage.shoppingCount) {
		Login.getLoginfo(callback_);
	} else {
		$count_.html(sessionStorage.shoppingCount);
	}
	
	function callback_(loginfo) {
		if (loginfo) {
			$.getJSON(getCountPath_, {}, function(data){
				if (data.status != 0) {
					showMsg(data.message, 'error');
					return;
				}
				var count = data.result;
				sessionStorage.shoppingCount = count;
				$count_.html(count);
			});
		}
	}
 }
 shoppingCount();

//标题头
$(function() {
	var isDoing = false;
	var preScrollTop = $(window).scrollTop();
	$(window).scroll(function() {
		if (isDoing) {
			return;
		}
		setTimeout(function() {
			var curScrollTop = $(window).scrollTop();
			if (curScrollTop < preScrollTop) {
				isDoing = true;
				$("#header").fadeIn(function() {
					preScrollTop = $(window).scrollTop();
					isDoing = false;
				});
			} else if (curScrollTop > preScrollTop) {
				isDoing = true;
				$("#header").fadeOut(function() {
					preScrollTop = $(window).scrollTop();
					isDoing = false;
				});
			}
		},200);
		
	});
});

// 商品列表排版类型
$(function() {
	var KEY = "goodslist_dtp";
	var dtp = getLocalStorage(KEY);
	
	if (parseInt(dtp) === 2) {
		$("header .store .tab a.st").addClass("st2");
		$("ul").each(function() {
			if ($(this).hasClass("goodlist")) {
				$(this).removeClass("goodlist").addClass("goodlist2");
			}
		})
	}
	
	$("header .store .tab a.st").click(function() {
		$(this).toggleClass("st2");
		// $("ul.goodslist2")获取不到对象
		$("ul").each(function() {
			if ($(this).hasClass("goodlist")) {
				$(this).removeClass("goodlist").addClass("goodlist2");
				setLocalStorage(KEY, 2);
			} else if ($(this).hasClass("goodlist2")) {
				$(this).removeClass("goodlist2").addClass("goodlist");
				setLocalStorage(KEY, 1);
			}
		})
	});
})

function showMsg(msg, type) {
	var $el = $('.msgClass');
	if ($el.length == 0) {
		$el = $("<div class='msgClass'></div>");
		$("body").prepend($el);
	}
	if (!msg)return $el;
	var html = '<div class="' + type + '">'+ msg +'</div>';
	$el.html(html);
    if (type != "load" && !($el.is(':animated'))) {
    	$el.stop(true,true).css({
            left: '20px',
            opacity: 0
        }).delay(100).show().animate({
            left: '-4px',
            opacity: 1
        }, 150).animate({
            left: '3px'
        }, 80).animate({
            left: 0
        }, 80).delay(500).stop().show().delay(1000).animate({
            opacity: 0
        }, 500, function(){
        	$el.hide();
        });
    } else {
    	$el.stop(true,true).css({
            left: 0,
            opacity: 1
        }).show();
    }
    return $el;
}

$(function() {
	$("#main .boxw").css({'background-color':"#ffffff", "min-height": $(window).height()});
	$(".goodlist").each(function() {
		$(this).find("li:gt(0):odd").css("clear","both");
	});
	
});

/**
 * 导航菜单
 */
$(document).on('click', "header .store a.more", function() {
	$("header .store div.more").fadeToggle();
});

/*function launchIntoFullscreen(element) {
  if(element.requestFullscreen) {
    element.requestFullscreen();
  } else if(element.mozRequestFullScreen) {
    element.mozRequestFullScreen();
  } else if(element.webkitRequestFullscreen) {
    element.webkitRequestFullscreen();
  } else if(element.msRequestFullscreen) {
    element.msRequestFullscreen();
  }
}
$(document).one('click', function() {
	launchIntoFullscreen(document.documentElement);
})*/

